﻿using System;
using System.Collections.Generic;
using System.Linq;
using NetSurveillance.WebApp.DataServices.Models;
using ServiceStack.OrmLite;

namespace NetSurveillance.WebApp.DataServices.Implementations
{
    public class TaskService : BaseService<Task>
    {
        public TaskService(string connStr, IOrmLiteDialectProvider provider = null)
            : base(connStr, provider)
        {
        }

        public override IEnumerable<Task> GetAllModels(bool ignoreDeleted = false,
                                                       System.Linq.Expressions.Expression<Func<Task, bool>> predicate = null)
        {
            var tasks = base.GetAllModels(ignoreDeleted, predicate);
            var allModels = tasks as List<Task> ?? tasks.ToList();
            if (allModels.Count > 0)
            {
                using (var db = DbFactory.OpenDbConnection())
                {
                    var createdUserIds = allModels.Select(p => p.CreateUserId);
                    var users = db.Ids<User>(createdUserIds);
                    foreach (var user in users)
                    {
                        foreach (var taskEntry in tasks.Where(taskEntry => taskEntry.CreateUserId == user.Id))
                        {
                            taskEntry.CreatedUser = user;
                        }
                    }
                }
            }
            return allModels;
        }

        public Task GetRunningTask()
        {
            using (var db = DbFactory.OpenDbConnection())
            {
                var runningTask = db.Select<Task>(p => p.TaskStatus == TaskStatusType.Running ||
                                                       p.TaskStatus == TaskStatusType.Suspend).FirstOrDefault();
                return runningTask;
            }
        }

        public Task GetLastTask()
        {
            using (var db = DbFactory.OpenDbConnection())
            {
                const string searchSql =
                    "select * from \"Tasks\" where \"StatusToken\" != 0 order by \"Id\" desc limit 1";
                var task = db.QuerySingle<Task>(searchSql, null);
                return task;
            }
        }
    }
}